const Task = require('../models/Task');
const asyncWrapper = require('../utils/asyncWrapper');

const returnAllTask = async (res, message = '请求成功') => {
   const tasks = await Task.find();
   res.data(
      {
         list: tasks,
      },
      message
   );
};

const getTasks = async (req, res) => {
   const _id = req.query.id;
   const tasks = _id
      ? await Task.find({
           _id,
        })
      : await Task.find();
   res.data({
      list: tasks,
   });
};

const createTask = async (req, res) => {
   await Task.create({
      title: req.body.title,
   });
   returnAllTask(res, '添加成功');
};

const updateTask = asyncWrapper(async (req, res, next) => {
   const data = req.body;
   if (data.completed !== undefined) {
      if(data.completed){
         data.completed_time = new Date().toISOString();
      }else{
         data.completed_time = ''
      }
   }
   await Task.findOneAndUpdate({ _id: req.body.id }, data);
   returnAllTask(res, '更新成功');
});

const removeTask = asyncWrapper(async (req, res) => {
   await Task.findOneAndRemove({
      _id: req.body.id,
   });
   returnAllTask(res, '删除成功');
});

module.exports = {
   getTasks,
   createTask,
   updateTask,
   removeTask,
};
